<template>
  <PageLoader :is-page-loading="isPageLoading" :is-data-loading="isDataLoading" :has-error="hasError"
    :error-message="errorMessage" loading-title="正在加载热门产品..." loading-message="请稍候" @retry="reloadPage">

    <!-- 页面内容 -->
    <div class="min-h-screen bg-gradient-to-br from-gray-50 via-white to-gray-100 relative">
      <!-- 导航栏 -->
      <AppHeader :show-back-button="false" :show-nav-menu="true" :show-breadcrumb="false" :show-location="true"
        :show-search-button="true" :show-notification-button="true" :show-decorations="false" logo-size="large" />

      <!-- Hero 区域 -->
      <section class="relative py-12 bg-gradient-to-br from-blue-50 via-white to-indigo-50">
        <div class="container mx-auto px-6">
          <div class="text-center max-w-4xl mx-auto">
            <div class="inline-flex items-center justify-center w-20 h-20 bg-gradient-to-r from-blue-500 to-indigo-500 rounded-2xl shadow-lg shadow-blue-500/30 mb-6">
              <i class="bi bi-pc-display-horizontal text-white text-3xl"></i>
            </div>
            <h1 class="text-4xl md:text-5xl font-bold text-gray-900 mb-4 leading-tight">
              专业级
              <span class="bg-gradient-to-r from-blue-600 to-indigo-600 bg-clip-text text-transparent">PC硬件</span>
              精选商城
            </h1>
            <p class="text-lg text-gray-600 mb-8 leading-relaxed max-w-2xl mx-auto">
              汇聚全球顶级品牌，提供专业的硬件解决方案，让每一台电脑都发挥极致性能
            </p>
            <div class="flex flex-col sm:flex-row gap-4 justify-center">
              <NuxtLink to="/products"
                class="inline-flex items-center px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition-all duration-300 shadow-lg hover:shadow-xl transform hover:-translate-y-1">
                <i class="bi bi-collection mr-2"></i>
                浏览全部产品
              </NuxtLink>
              <button @click="scrollToProducts"
                class="inline-flex items-center px-6 py-3 border-2 border-blue-600 text-blue-600 hover:bg-blue-600 hover:text-white font-semibold rounded-lg transition-all duration-300">
                <i class="bi bi-arrow-down mr-2"></i>
                查看热门推荐
              </button>
            </div>
          </div>
        </div>
        
        <!-- 装饰性元素 -->
        <div class="absolute top-0 left-0 w-full h-full overflow-hidden pointer-events-none">
          <div class="absolute top-16 left-8 w-24 h-24 bg-blue-200/20 rounded-full blur-xl animate-pulse"></div>
          <div class="absolute bottom-16 right-8 w-32 h-32 bg-indigo-200/20 rounded-full blur-xl animate-pulse delay-1000"></div>
          <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-48 h-48 bg-blue-100/15 rounded-full blur-2xl animate-pulse delay-500"></div>
        </div>
      </section>

      <!-- 特色服务 -->
      <section class="py-16 bg-white">
        <div class="container mx-auto px-6">
          <div class="grid md:grid-cols-4 gap-8">
            <div class="text-center group">
              <div class="w-16 h-16 mx-auto mb-4 bg-blue-100 rounded-xl flex items-center justify-center group-hover:bg-blue-200 transition-colors duration-300">
                <i class="bi bi-truck text-blue-600 text-2xl"></i>
              </div>
              <h3 class="font-semibold text-gray-900 mb-2">免费配送</h3>
              <p class="text-gray-600 text-sm">全国包邮，快速送达</p>
            </div>
            <div class="text-center group">
              <div class="w-16 h-16 mx-auto mb-4 bg-green-100 rounded-xl flex items-center justify-center group-hover:bg-green-200 transition-colors duration-300">
                <i class="bi bi-shield-check text-green-600 text-2xl"></i>
              </div>
              <h3 class="font-semibold text-gray-900 mb-2">品质保证</h3>
              <p class="text-gray-600 text-sm">正品保障，质量可靠</p>
            </div>
            <div class="text-center group">
              <div class="w-16 h-16 mx-auto mb-4 bg-purple-100 rounded-xl flex items-center justify-center group-hover:bg-purple-200 transition-colors duration-300">
                <i class="bi bi-headset text-purple-600 text-2xl"></i>
              </div>
              <h3 class="font-semibold text-gray-900 mb-2">专业服务</h3>
              <p class="text-gray-600 text-sm">技术支持，贴心服务</p>
            </div>
            <div class="text-center group">
              <div class="w-16 h-16 mx-auto mb-4 bg-orange-100 rounded-xl flex items-center justify-center group-hover:bg-orange-200 transition-colors duration-300">
                <i class="bi bi-arrow-repeat text-orange-600 text-2xl"></i>
              </div>
              <h3 class="font-semibold text-gray-900 mb-2">售后无忧</h3>
              <p class="text-gray-600 text-sm">30天退换，两年保修</p>
            </div>
          </div>
        </div>
      </section>

      <!-- 热门产品 -->
      <section id="products" class="py-16 bg-gray-50">
        <div class="container mx-auto px-6">
          <div class="text-center mb-12">
            <div class="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-red-500 to-orange-500 rounded-xl shadow-lg shadow-red-500/30 mb-4">
              <i class="bi bi-fire text-white text-2xl"></i>
            </div>
            <h2 class="text-3xl font-bold text-gray-900 mb-4">热门产品推荐</h2>
            <p class="text-lg text-gray-600">精选最受欢迎的PC硬件产品</p>
          </div>

          <!-- 空状态 -->
          <div v-if="featuredProducts.length === 0" class="text-center py-16">
            <div class="bg-white rounded-2xl p-12 shadow-lg max-w-md mx-auto">
              <div class="text-6xl mb-6 text-gray-300">
                <i class="bi bi-inbox"></i>
              </div>
              <h3 class="text-2xl font-semibold text-gray-900 mb-4">暂无热门产品</h3>
              <p class="text-gray-600 mb-8">商家还没有上传产品，请稍后再来查看</p>
              <button @click="reloadPage"
                class="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors duration-300">
                <i class="bi bi-arrow-clockwise mr-2"></i>
                重新加载
              </button>
            </div>
          </div>
  
          <!-- 产品网格 -->
          <div v-else class="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
            <div v-for="product in featuredProducts" :key="product.id"
              class="bg-white rounded-2xl border border-gray-200 shadow-lg hover:shadow-xl overflow-hidden transition-all duration-300 transform hover:-translate-y-2 group">
              
              <!-- 产品图片 -->
              <div class="relative h-56 bg-gray-50 border-b border-gray-100">
                <div v-if="product.image" class="product-image-container">
                  <img :src="product.image" :alt="product.name"
                    class="w-full h-full object-contain p-4 group-hover:scale-105 transition-transform duration-300"
                    @error="$event.target.style.display = 'none'">
                </div>
                <div v-else class="product-placeholder">
                  <i :class="getHomeProductIcon(product.name)" class="text-4xl text-gray-400"></i>
                  <span class="product-type text-sm text-gray-500 mt-2">{{ getProductTypeName(product.name) }}</span>
                </div>

                <!-- 热门标签 -->
                <div class="absolute top-3 right-3">
                  <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-red-100 text-red-600 border border-red-200">
                    <i class="bi bi-fire mr-1"></i>热门
                  </span>
                </div>
              </div>

              <!-- 产品信息 -->
              <div class="p-6">
                <h3 class="font-semibold text-gray-900 text-lg mb-2 line-clamp-2">{{ product.name }}</h3>
                <p class="text-gray-600 text-sm mb-4 line-clamp-2">{{ product.description }}</p>

                <div class="flex items-center justify-between mb-4">
                  <div class="text-2xl font-bold text-blue-600">¥{{ product.price.toLocaleString() }}</div>
                  <div class="flex">
                    <i v-for="i in 5" :key="i" :class="i <= product.rating ? 'text-yellow-400' : 'text-gray-300'"
                      class="bi bi-star-fill text-sm"></i>
                  </div>
                </div>

                <button @click="viewProduct(product.id)"
                  class="w-full px-4 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors duration-300">
                  查看详情
                </button>
              </div>
            </div>
          </div>

          <!-- 查看全部按钮 -->
          <div v-if="featuredProducts.length > 0" class="text-center mt-12">
            <NuxtLink to="/products"
              class="inline-flex items-center px-8 py-4 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white font-semibold rounded-xl transition-all duration-300 shadow-lg hover:shadow-xl transform hover:-translate-y-1">
              <i class="bi bi-collection mr-2"></i>
              浏览全部产品
            </NuxtLink>
          </div>
        </div>
      </section>

      <!-- 装机配置推荐 -->
      <section class="py-16 bg-white">
        <div class="container mx-auto px-6">
          <div class="text-center mb-12">
            <div class="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-green-500 to-emerald-500 rounded-xl shadow-lg shadow-green-500/30 mb-4">
              <i class="bi bi-cpu text-white text-2xl"></i>
            </div>
            <h2 class="text-3xl font-bold text-gray-900 mb-4">装机配置推荐</h2>
            <p class="text-lg text-gray-600">根据不同需求精心搭配的配置方案</p>
          </div>

          <!-- 空状态 -->
          <div v-if="configurations.length === 0" class="text-center py-16">
            <div class="bg-gray-50 rounded-2xl p-12 max-w-md mx-auto">
              <div class="text-6xl mb-6 text-gray-300">
                <i class="bi bi-cpu"></i>
              </div>
              <h3 class="text-2xl font-semibold text-gray-900 mb-4">暂无配置推荐</h3>
              <p class="text-gray-600 mb-8">商家还没有上传配置方案，请稍后再来查看</p>
              <button @click="reloadPage"
                class="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors duration-300">
                <i class="bi bi-arrow-clockwise mr-2"></i>
                重新加载
              </button>
            </div>
          </div>

          <!-- 配置列表 -->
          <div v-else class="grid md:grid-cols-3 gap-8">
            <div v-for="config in configurations" :key="config.id"
              class="bg-white rounded-2xl border border-gray-200 shadow-lg hover:shadow-xl overflow-hidden transition-all duration-300 transform hover:-translate-y-2">
              
              <div class="p-8 border-b border-gray-100">
                <div class="flex items-center justify-between mb-4">
                  <h3 class="text-2xl font-bold text-gray-900">{{ config.name }}</h3>
                  <span :class="getBadgeClass(config.badge)" class="px-3 py-1 rounded-full text-sm font-medium">
                    {{ config.badge }}
                  </span>
                </div>
                <p class="text-gray-600 mb-4">{{ config.description }}</p>
                <div class="text-3xl font-bold text-blue-600 mb-2">¥{{ config.price.toLocaleString() }}</div>
                <div class="text-sm text-gray-500">预估性能分数：{{ config.score }}</div>
              </div>

              <div class="p-8">
                <div class="space-y-3 mb-6">
                  <div v-for="component in config.components" :key="component.type"
                    class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                    <span class="text-gray-600 text-sm font-medium">{{ component.type }}</span>
                    <span class="text-gray-900 text-sm font-semibold">{{ component.name }}</span>
                  </div>
                </div>

                <button @click="viewProduct(config.id)"
                  class="w-full px-4 py-3 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition-colors duration-300">
                  选择此配置
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- 品牌展示 -->
      <section class="py-12 bg-gray-50">
        <div class="container mx-auto px-6">
          <div class="text-center mb-8">
            <div class="inline-flex items-center justify-center w-12 h-12 bg-gradient-to-r from-purple-500 to-pink-500 rounded-lg shadow-lg shadow-purple-500/30 mb-3">
              <i class="bi bi-award text-white text-lg"></i>
            </div>
            <h2 class="text-2xl font-bold text-gray-900 mb-2">合作品牌</h2>
            <p class="text-gray-600">与全球知名品牌深度合作</p>
          </div>
          <div class="grid grid-cols-3 md:grid-cols-6 gap-4">
            <div v-for="brand in ['Intel', 'AMD', 'NVIDIA', 'ASUS', 'MSI', 'Corsair']" :key="brand"
              class="bg-white rounded-lg p-4 shadow-sm hover:shadow-md transition-all duration-300 flex items-center justify-center group">
              <span class="text-gray-600 font-semibold text-sm group-hover:text-blue-600 transition-colors duration-300">{{ brand }}</span>
            </div>
          </div>
        </div>
      </section>

      <!-- 页脚 -->
      <footer class="bg-gray-900 text-white py-16">
        <div class="container mx-auto px-6">
          <div class="grid md:grid-cols-4 gap-8 mb-8">
            <div>
              <div class="flex items-center mb-4">
                <AppLogo size="medium" :show-decorations="false" />
              </div>
              <p class="text-gray-400 mb-4">专业的PC硬件产品和装机服务提供商</p>
              <div class="flex space-x-4">
                <a href="#" class="text-gray-400 hover:text-white transition-colors duration-200">
                  <i class="bi bi-facebook text-xl"></i>
                </a>
                <a href="#" class="text-gray-400 hover:text-white transition-colors duration-200">
                  <i class="bi bi-twitter text-xl"></i>
                </a>
                <a href="#" class="text-gray-400 hover:text-white transition-colors duration-200">
                  <i class="bi bi-instagram text-xl"></i>
                </a>
              </div>
            </div>
            <div>
              <h3 class="text-lg font-semibold mb-4">产品分类</h3>
              <ul class="space-y-2 text-gray-400">
                <li><a href="#" class="hover:text-white transition-colors duration-200">处理器</a></li>
                <li><a href="#" class="hover:text-white transition-colors duration-200">显卡</a></li>
                <li><a href="#" class="hover:text-white transition-colors duration-200">主板</a></li>
                <li><a href="#" class="hover:text-white transition-colors duration-200">内存</a></li>
              </ul>
            </div>
            <div>
              <h3 class="text-lg font-semibold mb-4">客户服务</h3>
              <ul class="space-y-2 text-gray-400">
                <li><a href="#" class="hover:text-white transition-colors duration-200">联系我们</a></li>
                <li><a href="#" class="hover:text-white transition-colors duration-200">售后服务</a></li>
                <li><a href="#" class="hover:text-white transition-colors duration-200">配送信息</a></li>
                <li><a href="#" class="hover:text-white transition-colors duration-200">退换政策</a></li>
              </ul>
            </div>
            <div>
              <h3 class="text-lg font-semibold mb-4">关于我们</h3>
              <ul class="space-y-2 text-gray-400">
                <li><a href="#" class="hover:text-white transition-colors duration-200">公司介绍</a></li>
                <li><a href="#" class="hover:text-white transition-colors duration-200">招聘信息</a></li>
                <li><a href="#" class="hover:text-white transition-colors duration-200">隐私政策</a></li>
                <li><a href="#" class="hover:text-white transition-colors duration-200">服务条款</a></li>
              </ul>
            </div>
          </div>
          <div class="border-t border-gray-800 pt-8 text-center text-gray-400">
            <p>© 2024 xlCig. 保留所有权利.</p>
          </div>
        </div>
      </footer>
    </div>
  </PageLoader>
</template>

<script setup>
import { productsApi } from '~/utils/api/products'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

// 响应式数据
const featuredProducts = ref([])
const configurations = ref([])

// 简化的加载状态管理
const isPageLoading = ref(true)
const isDataLoading = ref(true)
const hasError = ref(false)
const errorMessage = ref('')

// 滚动到产品区域
const scrollToProducts = () => {
  const element = document.getElementById('products')
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' })
  }
}

// 获取徽章样式
const getBadgeClass = (badge) => {
  const badgeClasses = {
    '超值': 'bg-green-100 text-green-600 border border-green-200',
    '推荐': 'bg-blue-100 text-blue-600 border border-blue-200',
    '顶级': 'bg-purple-100 text-purple-600 border border-purple-200'
  }
  return badgeClasses[badge] || 'bg-gray-100 text-gray-600 border border-gray-200'
}

// 简化的加载函数
const loadPageData = async () => {
  try {
    console.log('首页开始加载数据...')
    isPageLoading.value = true
    isDataLoading.value = true
    hasError.value = false

    // 加载数据
    const [products, configs] = await Promise.all([
      fetchFeaturedProducts(),
      fetchConfigurations()
    ])

    console.log('首页数据加载完成:', {
      productsCount: products.length,
      configsCount: configs.length
    })

    // 使用 nextTick 确保状态更新在下一个渲染周期生效
    await nextTick()

    // 更新状态
    isPageLoading.value = false
    isDataLoading.value = false

    console.log('首页状态更新完成:', {
      isPageLoading: isPageLoading.value,
      isDataLoading: isDataLoading.value,
      productsCount: featuredProducts.value.length,
      configsCount: configurations.value.length
    })

  } catch (error) {
    console.error('首页数据加载失败:', error)
    hasError.value = true
    errorMessage.value = error.message || '页面加载失败'
    isPageLoading.value = false
    isDataLoading.value = false
  }
}

// 重新加载页面
const reloadPage = () => {
  loadPageData()
}

// 页面挂载时加载数据
onMounted(() => {
  console.log('首页组件 onMounted 触发')
  loadPageData()
  
  // 应用首页专用滚动条样式
  if (process.client) {
    document.body.classList.add('home-page-scrollbar')
  }
})

// 页面卸载时清理
onUnmounted(() => {
  console.log('首页组件卸载')
  
  // 移除首页专用滚动条样式
  if (process.client) {
    document.body.classList.remove('home-page-scrollbar')
  }
})

// 监听路由变化
watch(() => route.path, (newPath, oldPath) => {
  console.log('首页路由变化:', oldPath, '->', newPath)
  if (newPath === '/') {
    console.log('返回首页，重新加载数据')
    loadPageData()
    
    // 重新应用首页专用滚动条样式
    if (process.client) {
      document.body.classList.add('home-page-scrollbar')
    }
  } else {
    // 离开首页时移除专用滚动条样式
    if (process.client) {
      document.body.classList.remove('home-page-scrollbar')
    }
  }
})

// 获取热门产品
const fetchFeaturedProducts = async () => {
  try {
    const response = await productsApi.getHotProducts(4)
    if (response.success && response.data) {
      const products = response.data.map(config => ({
        id: config.id,
        name: config.name,
        price: config.price,
        rating: 4.5, // 默认评分
        image: config.images && config.images.length > 0 ? config.images[0] : '',
        description: config.description || '专业电脑配置'
      }))

      featuredProducts.value = products
      return products
    } else {
      featuredProducts.value = []
      return []
    }
  } catch (error) {
    console.error('获取热门产品失败:', error)
    featuredProducts.value = []
    return []
  }
}

// 获取配置推荐
const fetchConfigurations = async () => {
  try {
    const response = await productsApi.getFeaturedProducts({ limit: 3 })
    if (response.success && response.data && response.data.length > 0) {
      const configs = response.data.map((config, index) => {
        const badges = ['超值', '推荐', '顶级']
        const badgeClasses = [
          'px-3 py-1 bg-green-500/20 text-green-300 rounded-full text-sm font-medium',
          'px-3 py-1 bg-cyan-500/20 text-cyan-300 rounded-full text-sm font-medium',
          'px-3 py-1 bg-purple-500/20 text-purple-300 rounded-full text-sm font-medium'
        ]

        // 解析配置规格
        let components = []
        if (config.specs) {
          try {
            const specs = typeof config.specs === 'string' ? JSON.parse(config.specs) : config.specs
            components = Object.entries(specs).slice(0, 4).map(([key, value]) => ({
              type: getSpecDisplayName(key),
              name: value
            }))
          } catch (e) {
            console.error('解析配置规格失败:', e)
            components = []
          }
        }

        return {
          id: config.id,
          name: config.name,
          price: config.price,
          score: 85 + index * 5, // 模拟性能分数
          badge: badges[index] || '推荐',
          badgeClass: badgeClasses[index] || badgeClasses[1],
          description: config.description || getCategoryDescription(config.category),
          components: components
        }
      })

      configurations.value = configs
      return configs
    } else {
      configurations.value = []
      return []
    }
  } catch (error) {
    console.error('获取配置推荐失败:', error)
    configurations.value = []
    return []
  }
}

// 辅助函数
const getSpecDisplayName = (key) => {
  const specNames = {
    cpu: 'CPU',
    gpu: '显卡',
    motherboard: '主板',
    memory: '内存',
    storage: '存储',
    power: '电源',
    case: '机箱',
    cooler: '散热器',
    display: '显示器'
  }
  return specNames[key] || key.toUpperCase()
}

const getCategoryDescription = (category) => {
  const descriptions = {
    office: '适合日常办公和学习使用的高性价比配置',
    gaming: '专为游戏优化的高性能配置',
    workstation: '专业工作站配置，适合内容创作和专业应用'
  }
  return descriptions[category] || '专业电脑配置方案'
}

// 产品相关方法
const viewProduct = (productId) => {
  router.push(`/products/${productId}`)
}

const getHomeProductIcon = (productName) => {
  if (productName.includes('RTX') || productName.includes('RX') || productName.includes('显卡')) {
    return 'bi bi-gpu-card text-cyan-400 text-4xl'
  }
  if (productName.includes('Intel') || productName.includes('AMD') || productName.includes('Ryzen') || productName.includes('Core')) {
    return 'bi bi-cpu text-orange-400 text-4xl'
  }
  if (productName.includes('主板') || productName.includes('STRIX') || productName.includes('MAG')) {
    return 'bi bi-motherboard text-green-400 text-4xl'
  }
  if (productName.includes('电源') || productName.includes('PSU') || productName.includes('Power')) {
    return 'bi bi-lightning text-yellow-400 text-4xl'
  }
  return 'bi bi-pc-display text-gray-400 text-4xl'
}

const getProductTypeName = (productName) => {
  if (productName.includes('RTX') || productName.includes('RX') || productName.includes('显卡')) {
    return '显卡'
  }
  if (productName.includes('Intel') || productName.includes('AMD') || productName.includes('Ryzen') || productName.includes('Core')) {
    return 'CPU'
  }
  if (productName.includes('主板') || productName.includes('STRIX') || productName.includes('MAG')) {
    return '主板'
  }
  if (productName.includes('电源') || productName.includes('PSU') || productName.includes('Power')) {
    return '电源'
  }
  return 'PC配件'
}

// 添加 console.log 来调试渲染
console.log('首页组件渲染, 状态:', {
  isPageLoading: isPageLoading.value,
  isDataLoading: isDataLoading.value,
  hasError: hasError.value,
  productsCount: featuredProducts.value.length,
  configsCount: configurations.value.length
})
</script>

<style scoped>
/* 产品图片容器 */
.product-image-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 产品Placeholder样式 */
.product-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.product-type {
  font-weight: 500;
}

/* 文本截断 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 平滑滚动 */
html {
  scroll-behavior: smooth;
}

/* 悬停效果 */
.group:hover .group-hover\:scale-105 {
  transform: scale(1.05);
}

.group:hover .group-hover\:bg-blue-200 {
  background-color: rgb(191 219 254);
}

.group:hover .group-hover\:bg-green-200 {
  background-color: rgb(187 247 208);
}

.group:hover .group-hover\:bg-purple-200 {
  background-color: rgb(221 214 254);
}

.group:hover .group-hover\:bg-orange-200 {
  background-color: rgb(254 215 170);
}
</style>
